<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\mill\builder\Admin;
use app\mill\builder\ZBuilder;
use app\mill\model\Client as ClientModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Stat as StatModel;
use app\user\model\User as UserModel;
use app\user\model\Role as RoleModel;
use app\admin\model\Menu as MenuModel;
use think\facade\Hook;
use think\Db;
use think\facade\Env;

/**
 * 员工管理
 * @package app\user\admin
 */
class User extends Admin
{
    //初始化
    protected function initialize(){
        parent::initialize();
        GiveModel::init();
    }
    //员工列表
    public function lists()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $top_html = StatModel::userHtml();

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('admin_user')
            ->alias('u')
            ->field('u.*,g.name as group_name,m.name as mill_name')
            ->leftJoin('admin_user_group g','u.group=g.id')
            ->leftJoin('admin_user_mill m','u.mill_id=m.id')
            ->where($map)
            ->where("u.id <> 1")
            ->group('u.id')
            ->order('u.id desc')
            ->paginate()
            ->each(function ($v){

                return $v;

            })
        ;

        // 角色列表
        if (session('user_auth.role') != 1) {
            $role_list = RoleModel::getTree(null, false, session('user_auth.role'));
        } else {
            $role_list = RoleModel::getTree();
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('用户列表('.$data_list->total().')') // 页面标题
            ->setTableName('admin_user') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            //->hideCheckbox()
            ->setSearch(['u.nickname' => '昵称','u.mobile' => '电话']) // 设置搜索参数
            ->setSearchArea([
                ['select:2', 'u.group', '所属部门','','',ClientModel::getGroupList()],
                ['select:2', 'u.mill_id', '所属车间','','',ClientModel::getMillList()],
            ])
            ->addColumns([ // 批量添加列
                ['nickname', '用户昵称','','','','',['group'=>'用户信息']],
                ['mobile', '联系方式','','','','',['group'=>'用户信息']],
                ['role', '用户权限', $role_list,'','','',['group'=>'用户信息']],
                ['mill_id', '所属车间', ClientModel::getMillList(),'','','',['group'=>'用户信息']],
                ['group', '所属组', ClientModel::getGroupList(),'','','',['group'=>'用户信息']],
                ['job', '用户职务','','','','',['group'=>'用户信息']],
                ['belong', '用户归属','','','','',['group'=>'用户信息']],
                ['create_time', '注册时间','date','','','',['group'=>'行为记录']],
                ['last_login_time', '最近在线','date','','','',['group'=>'行为记录']],
                ['status','锁定','switch2','','','',['group'=>'启用']],
                ['right_button','操作','btn','','','',['group'=>'操作']],
            ])
            ->addTopButton('add',['title' => '添加用户','href'=>url('mill/user/add'),'class'=>'btn btn-default','float'=>'right'])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->addRightButton('add',['title' => '修改','href' => url('mill/user/add',[ 'id' => '__id__']),'class'=>'btn bg-default'])
            ->addRightButton('delete', ['title' => '删除', 'href' => url('mill/user/delete',[ 'id' => '__id__']),'class'=>'btn btn-danger ajax-get confirm'],false)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 130,
                'mobile'  => 130,
                'sales'  => 130,
                'back'  => 130,
                'nickname'  => 130,
                'sales_mobile'  => 130,
                'status'  => 130,
                'right_button'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    //员工审核列表
    public function userVerify()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $top_html = StatModel::userHtml();

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['register_status','=',0];
        // 数据列表
        $data_list = Db::name('admin_user')
            ->alias('u')
            ->field('u.*,g.name as group_name,m.name as mill_name')
            ->leftJoin('admin_user_group g','u.group=g.id')
            ->leftJoin('admin_user_mill m','u.mill_id=m.id')
            ->where($map)
            ->where("u.id <> 1")
            ->group('u.id')
            ->order('u.id desc')
            ->paginate();

        // 角色列表
        if (session('user_auth.role') != 1) {
            $role_list = RoleModel::getTree(null, false, session('user_auth.role'));
        } else {
            $role_list = RoleModel::getTree();
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('用户审核('.$data_list->total().')') // 页面标题
            ->setTableName('admin_user') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            //->hideCheckbox()
            ->setSearch(['u.nickname' => '昵称','u.mobile' => '电话']) // 设置搜索参数
            ->setSearchArea([
                ['select:2', 'u.group', '所属部门','','',ClientModel::getGroupList()],
                ['select:2', 'u.mill_id', '所属车间','','',ClientModel::getMillList()],
            ])
            ->addColumns([ // 批量添加列
                ['nickname', '用户昵称','','','','',['group'=>'用户信息']],
                ['mobile', '联系方式','','','','',['group'=>'用户信息']],
                ['role', '用户权限', $role_list,'','','',['group'=>'用户信息']],
                ['mill_id', '所属车间', ClientModel::getMillList(),'','','',['group'=>'用户信息']],
                ['group', '所属组', ClientModel::getGroupList(),'','','',['group'=>'用户信息']],
                ['job', '用户职务','','','','',['group'=>'用户信息']],
                ['belong', '用户归属','','','','',['group'=>'用户信息']],
                ['create_time', '注册时间','date','','','',['group'=>'用户信息']],
                ['right_button','操作','btn','','','',['group'=>'操作']],
            ])
            ->addRightButton('add',['title' => '通过','href' => url('mill/user/add',[ 'id' => '__id__','status'=>1,'register_status'=>1]),'class'=>'btn bg-default'])
            ->addRightButton('delete', ['title' => '拒绝', 'href' => url('mill/user/delete',[ 'id' => '__id__']),'class'=>'btn btn-danger ajax-get confirm'],false)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 130,
                'mobile'  => 130,
                'sales'  => 130,
                'back'  => 130,
                'nickname'  => 130,
                'sales_mobile'  => 130,
                'status'  => 130,
                'right_button'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    //新增
    public function add()
    {
        $id = input('id');
        $info = [];

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            if(!$id){
                $data['username'] = $data['mobile'];
                $result = $this->validate($data, 'User');
            }
            else$result = $this->validate($data, 'User.update');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            if (empty($data['group']))$this->error('请选择部门');
            if (empty($data['job']))$this->error('请填写职务');
            //if (empty($data['belong']))$this->error('请填写归属');

            // 如果没有填写密码，则不更新密码
            if ($data['password'] == '')unset($data['password']);

            $data['roles'] = isset($data['roles']) ? implode(',', $data['roles']) : '';

            if(!$id){
                if ($user = UserModel::create($data)) {
                    Hook::listen('user_add', $user);
                    // 记录行为
                    action_log('user_add', 'admin_user', $user['id'], UID);
                    $this->success('新增成功','','_parent_reload');
                }
            }
            else{
                if (UserModel::update($data)) {
                    $user = UserModel::get($data['id']);
                    Hook::listen('user_edit', $user);
                    // 记录行为
                    action_log('user_edit', 'admin_user', $user['id'], UID, get_nickname($user['id']));
                    $this->success('编辑成功','','_parent_reload');
                }
            }

            $this->error('操作失败');
        }

        $status = input('status');
        $register_status = input('register_status');
        //编辑
        if($id)$info = Db::name('admin_user')->where(['id'=>$id])->find();
        else{
            $status = 1;
            $register_status = 1;
        }
        unset($info['password']);
        if(is_numeric($status))$info['status'] = $status;
        if(is_numeric($register_status))$info['register_status'] = $register_status;

        // 角色列表
        if (session('user_auth.role') != 1) {
            $role_list = RoleModel::getTree(null, false, session('user_auth.role'));
        } else {
            $role_list = RoleModel::getTree();
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['ititle', 'ititle1', '用户项'],
                ['ititle', 'ititle2', '审批项'],
                ['text', 'nickname', '用户昵称'],
                ['select', 'role', '用户权限','',$role_list],
                ['text', 'mobile', '联系方式'],
                ['select', 'group', '所属组','',ClientModel::getGroupList()],
                ['text', 'password', '用户密码'],
                ['text', 'job', '用户职务'],
                ['select', 'mill_id', '所属车间','',ClientModel::getMillList()],
                //['text', 'belong', '用户归属'],
                ['textarea:12', 'note', '备注'],
                ['hidden','status'],
                ['hidden','register_status'],
            ])
            ->setFormData($info)
            ->fetch();
    }
    //删除
    public function delete($record = [])
    {
        $id = input('id');

        $re = Db::name('admin_user')->where([['id','in',$id]])->delete();
        if(false === $re)$this->error('删除失败');

        $this->success('操作成功');
    }

    //车间列表
    public function millLists()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $top_html = StatModel::userHtml();

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('admin_user_mill')
            ->where($map)
            ->order('id asc')
            ->paginate();

        //工艺
        $group_list = GiveModel::$role;

        foreach ($data_list as $k=>$v){
            $group_ids = explode(',',$v['group_ids']);

            foreach ($group_list as $gk=>$gv){
                $v["group_ids___{$gk}"] = in_array($gk,$group_ids)?1:0;
            }
            $data_list[$k] = $v;
        }

        $columns = [
            ['name', '车间','','','','',['group'=>'车间']],
        ];
        //工艺
        $group_list = GiveModel::$role;
        foreach ($group_list as $k=>$v){
            $columns[] = ["group_ids___{$k}", $v['name'],'switch','','','',['group'=>'工艺环节权限(扫码)']];
        }

        //JS
        $js = '<script type="text/javascript">
                
                function _tableDone() {
                    $(".switch").addClass("dch-switch");
                    $(".switch").removeClass("switch");
                    //点击查看已发货明细
                    $(".dch-switch").unbind("click");
                    $(".dch-switch").click(function () {
                        
                        var url = "'.url('millAdd').'";
                        var $switch = $(this).find("input:checkbox");
                        var field_val = ($switch.attr("data-field")).split("___");
                        var $data = {
                            id: $switch.data("id") || "",
                            checked: $switch.prop("checked"),
                            field: field_val[0],
                            value: field_val[1]
                        };
                        
                        // 发送ajax请求
                        Dolphin.loading();
                        $.post(url, $data).success(function(res) {
                            Dolphin.loading("hide");
                            if (res.code) {
                                Dolphin.notify(res.msg, "success");
                            } else {
                                Dolphin.notify(res.msg, "danger");
                                //$switch.prop("checked", !$switch.prop("checked"));
                                return false;
                            }
                        }).fail(function (res) {
                            Dolphin.loading("hide");
                            Dolphin.notify($(res.responseText).find("h1").text() || "服务器内部错误~", "danger");
                        });
                        
                    });
                }
                
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('车间权限') // 页面标题
            ->setTableName('admin_user_mill') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            ->hideCheckbox()
            // 批量添加列
            ->addColumns($columns)
            ->addTopButton('millAdd',['title' => '添加车间','href'=>url('mill/user/millAdd'),'class'=>'btn btn-default','float'=>'right'])
            ->addTopButton('giveGroupAdd',['title' => '添加工艺','href'=>url('mill/user/giveGroupAdd'),'class'=>'btn btn-default','float'=>'right'])
            ->addTopButton('millAdd2',['title' => '修改车间','href'=>url('mill/user/millAdd',['is_edit'=>1]),'class'=>'btn btn-default','float'=>'right'])
            ->addTopButton('giveGroupAdd2',['title' => '修改工艺','href'=>url('mill/user/giveGroupAdd',['is_edit'=>1]),'class'=>'btn btn-default','float'=>'right'])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->setExtraJs($js)
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 130,
                'mobile'  => 130,
                'sales'  => 130,
                'back'  => 130,
                'nickname'  => 130,
                'sales_mobile'  => 130,
                'status'  => 130,
                'right_button'  => 150,
            ])
            ->fetch(); // 渲染模板
    }

    //新增车间
    public function millAdd()
    {
        $id = input('id');
        $is_edit = input('is_edit');
        $info = [];

        if ($this->request->isPost()) {
            $data = input();

            //设置工艺权限
            if(isset($data['checked'])){
                $group_ids = Db::name('admin_user_mill')->where(['id'=>$id])->value($data['field']);
                $group_ids = explode(',',$group_ids);
                if($data['checked'] == 'true'){
                    if(!in_array($data['value'],$group_ids))$group_ids[] = $data['value'];
                }
                else{
                    $group_ids = array_diff($group_ids,[$data['value']]);
                }
                $group_ids = implode(',',$group_ids);
                Db::name('admin_user_mill')->where(['id'=>$id])->update([$data['field']=>trim($group_ids,',')]);

                $this->success('操作成功');
            }

            unset($data['id']);
            if($id)$re = Db::name('admin_user_mill')->where(['id'=>$id])->update($data);
            else $re = Db::name('admin_user_mill')->insert($data);

            if($re)$this->success('编辑成功','','_parent_reload');
            $this->error('操作失败');
        }

        //编辑
        if($id)$info = Db::name('admin_user')->where(['id'=>$id])->find();

        //工艺
        $group_list = GiveModel::$role;
        foreach ($group_list as $k=>$v){
            $group_list[$k] = $v['name'];
        }

        $title = '新增';
        $items = [
            ['text:12', 'name', '车间名称'],
            ['checkbox:12', 'group_ids', '工艺','',$group_list,array_keys($group_list)],
        ];
        if($is_edit){
            $items = [
                ['select:12', 'id', '选择车间','',ClientModel::getMillList()],
                ['text:12', 'name', '修改为'],
            ];
            $title = '修改';
        }

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            // 批量添加表单项
            ->addFormItems($items)
            ->setFormData($info)
            ->fetch();
    }

    //新增工艺
    public function giveGroupAdd()
    {
        $id = input('id');
        $is_edit = input('is_edit');
        $info = [];

        if ($this->request->isPost()) {
            $data = input();
            unset($data['id']);
            if(empty($data['give_title']))$this->error('请填写工艺名称');

            $data['name'] = "{$data['give_title']}部";

            //新增
            if(empty($id)){

                if(empty($data['give_sort']))$this->error('请填写工艺顺序');
                $is_give_sort = Db::name('admin_user_group')->where(['give_sort'=>$data['give_sort']])->count();
                if($is_give_sort > 0)$this->error('该工艺顺序已被占用，请更换其他顺序');

                $data['create_time'] = time();
                $data['update_time'] = time();
                //如果加入生产线，则新增产品表对应生产线的字段
                if($data['is_give']){
                    $sql = "ALTER TABLE `xxy_mill_order_archives_give` ADD COLUMN `status{$data['give_sort']}_time`  int(11) NOT NULL COMMENT '{$data['give_title']}时间';";
                    Db::query($sql);
                }
                $re = Db::name('admin_user_group')->insertGetId($data);
                Db::name('admin_user_group')->where(['id'=>$re])->update(['sort'=>$re]);

            }
            else $re = Db::name('admin_user_group')->where(['id'=>$id])->update($data);

            if($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        //工艺
        $group_list = GiveModel::$role;
        //最后一个生产线状态
        $last_give_status = GiveModel::$last_give_status;
        foreach ($group_list as $k=>$v){
            $group_list[$k] = $v['name'];
        }

        //['checkbox:12', 'group_ids', '工艺','',$group_list,array_keys($group_list)],
        $title = '新增';
        $items = [
            ['text:12', 'give_title', '工艺名称'],
            ['number:12', 'give_sort', '工艺顺序','',$last_give_status+1],
            ['hidden', 'app_page','speed'],//APP页面
            ['radio:12', 'is_give','加入生产线','',[0=>'不加入',1=>'加入'],1],//是否加入生产线
        ];
        if($is_edit){
            $items = [
                ['select:12', 'id', '选择工艺','',$group_list],
                ['text:12', 'give_title', '修改为'],
            ];
            $title = '修改';
        }

        $items[] = [];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            // 批量添加表单项
            ->addFormItems($items)
            ->setFormData($info)
            ->fetch();
    }

    //扫码员列表
    public function staffList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $top_html = StatModel::userHtml();

        // 获取查询条件
        $map = $this->getMap();

        //产品最后一个的状态
        $last_give_status = GiveModel::$last_give_status;

        // 数据列表
        $data_list = Db::name('mill_staff')
            ->alias('s')
            ->field("s.*,{$last_give_status} as last_give_status,count(DISTINCT c.id) as client_count,GROUP_CONCAT(DISTINCT o.id) as order_ids,sum(o.archives_number_sum) as number_sum,sum(o.archives_area_sum) as area_sum,sum(o.address_number) as address_number,sum(o.address_area) as address_area")
            ->leftJoin('mill_client c','c.sales_id=s.id')
            ->leftJoin('mill_order o','o.sales_id=s.id')
            ->where($map)
            ->where(['s.type'=>3])
            ->group('s.id')
            ->order('s.id desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('扫码员列表') // 页面标题
            ->setTableName('mill_staff') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            //->hideCheckbox()
            ->setSearch(['s.staff' => '扫码员','s.staff_mobile' => '手机号']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['staff', '扫码员','','','','badge-green',['group'=>'扫码员详情']],
                ['staff_mobile', '手机号','','','','',['group'=>'扫码员详情']],
                ['status','锁定','switch2','','','',['group'=>'启用']],
                ['right_button','操作','btn','','','',['group'=>'操作']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'left','lay-event'=>'quality-print'])
            ->addTopButton('add',['title' => '新增','href'=>url('mill/user/staffAdd'),'class'=>'btn btn-default','float'=>'left'])
            //->addTopButton('delete',['title' => '删除','href'=>url('mill/user/staffDelete'),'class'=>'btn btn-danger ajax-post confirm','target-form'=>'ids'],false)
            ->addRightButton('edit',['title' => '修改','href' => url('mill/user/staffAdd',[ 'id' => '__id__']),'class'=>'btn bg-default'])
            ->addRightButton('delete', ['title' => '删除', 'href' => url('mill/user/staffDelete',[ 'id' => '__id__']),'class'=>'btn btn-danger ajax-get confirm'],false)
            ->setRowList($data_list) // 设置表格数据
            //->setWidth('30%') // 设置表格宽度
            ->setColumnWidth([
                'id'  => 60,
                'status'  => 130,
                'right_button'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    //新增
    public function staffAdd()
    {
        $id = input('id');
        if (strpos($id, ',') !== false)$this->error('暂不支持批量修改');
        $info = [];

        if ($this->request->isPost()) {
            $data = input();

            if(empty($data['staff'])) $this->error('请输入名称');

            if($id)$re = Db::name('mill_staff')->where(['id'=>$id])->update($data);
            else $re = Db::name('mill_staff')->insertGetId($data);

            //关闭子窗口，并刷新父窗口
            if ($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id)$info = Db::name('mill_staff')->where(['id'=>$id])->find();

        return ZBuilder::make('form')
            ->setPageTitle('新增') // 页面标题
            ->addHidden('type',3)
            ->addFormItems([ // 批量添加表单项
                ['text:12||||must', 'staff', '扫码员名称'],
                //['static', 'static', ''],
                ['text:12', 'staff_mobile', '扫码员电话'],
                //['static', 'static', ''],
                //['radio:12', 'type', '人员类型','',ClientModel::$staff_type,3],
            ])
            ->setFormData($info)
            ->fetch();
    }
    //删除
    public function staffDelete()
    {

        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        $re = Db::name('mill_staff')->where([['id','in',$ids]])->delete();
        if(false === $re)$this->error('删除失败');

        $this->success('操作成功');
    }

}
